import React, { useState, useEffect } from 'react'
import { Col, Form, Input, Button, Table, Modal, Checkbox, InputNumber, Switch, message, Radio, } from 'antd'
import { PageHeaderWrapper } from '@ant-design/pro-layout'
import RenderButtom from '@/components/RenderButton'
import SearchBox from '@/components/SearchBox'
import {
  fetchMembershipCards,
  editWholeCashier,
  editWholeCashierStatus,
} from '@/services/distribution/setting'
import { formItemLayout } from '@/utils/utils'

const hasSearchBtn = JSON.parse(localStorage.getItem('hasSearchBtn'))
const col = [
  {
    title: '序号',
    dataIndex: 'sort',
    key: 'sort',
    render: (t, r, i) => <>{i + 1}</>
  },
  {
    title: '门店名称',
    dataIndex: 'storeName',
    key: 'storeName',
  },
  {
    title: '提成类型',
    dataIndex: 'commissionType',
    key: 'commissionType',
    render: t => <>{t == 0 ? `定额` : t == 1 ? '比例' : null}</>
  },
  {
    title: '提成值',
    dataIndex: 'commissionValue',
    key: 'commissionValue',
    render: t => <>{t ? `${t * 100}%` : null}</>
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    render: t => <>{t == 1 ? `开启` : '关闭'}</>
  },
]
const Cashier = props => {
  const { form } = props
  const { getFieldDecorator } = form
  const [data, setData] = useState([])
  const [record, setRecord] = useState([])
  const [visible, setVisible] = useState(false)
  const [isCheck, setCheck] = useState(false)
  const [type, setType] = useState('元')

  useEffect(() => {
    init()
  }, [])

  const init = async (params = {
    pageNo: 1,
    pageSize: 10
  }) => {
    const res = await fetchMembershipCards(params)
    res.code == 0 ? setData(res.data) : message.warning(res.msg)
  }

  const handleRequest = (res) => {
    if (res.code == 0) {
      setVisible(!visible)
      init()
    } else {
      message.warning(res.msg)   
    }
  }

  // 表单查询
  const handleSearch = e => {
    e.preventDefault()
    form.validateFields((err, values) => {
      console.log('Received values of form: ', values)

    })
  }
  // 表单清空
  const handleReset = e => {
    form.resetFields();
  }
  // 查询条件
  const getFields = () => {
    return(
      <Col span={8}>
        <Form.Item label={`名称`}>
          {getFieldDecorator(`id`, {})
            (<Input />)}
        </Form.Item>
      </Col>
    )
  }
  // 按钮处理
  const handleBtn = type => {
    if (record.length == 0 && type != 1) return message.warning('请选择一条数据')
    switch (type) {
      case 3: //edit
        return setVisible(!visible)
            
      default:
        break;
    }
  }

  const editData = e => {
    e.preventDefault()
    form.validateFields((err, values) => {
      console.log('Received values of form: ', values)
      !values.status ?
      editWholeCashierStatus({
        employeeCashRegisterSetting: {
          status: values.status ? '1' : '0',
          id: record[0].id,
        }
      }).then(res => handleRequest(res)) :
      editWholeCashier({
        employeeCashRegisterSetting: {
          ...record[0],
          ...values,
          status: values.status ? '1' : '0',
        }
      }).then(res => handleRequest(res))
    })
  }
  const rowSelection = {
    type: 'radio',
    onChange: (selectedRowKeys, selectedRows) => {
      setRecord(selectedRows)
      setType(selectedRows[0].commissionType ? selectedRows[0].commissionType == '0' ? '元' : '%' : null)
      console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
    },
  };
  return (
    <PageHeaderWrapper>
      <SearchBox handleReset={handleReset} handleSearch={handleSearch} getFields={getFields} />
      <RenderButtom click={handleBtn} />
      <Table 
        columns={col}
        dataSource={data}
        rowSelection={rowSelection}
        rowKey={r => r.id}
      />
      <Modal
        title='编辑'
        visible={visible}
        onOk={editData}
        onCancel={() => setVisible(!visible)}
      >
        <Form {...formItemLayout}>
          <Form.Item label="开关">
            {getFieldDecorator('status', {
              initialValue: record[0] && record[0].status == '1' ? true : false,
              valuePropName: 'checked',
            })(<Switch onChange={checked => setCheck(checked)} />)}
          </Form.Item>
          {(record[0] && record[0].status == '1' || isCheck) && <Form.Item label="员工收银提成类型">
            {getFieldDecorator('commissionType', {
              initialValue: record[0] && record[0].commissionType,
            })(<Radio.Group onChange={e => setType(e.target.value == '0' ? '元' : '%')}>
                <Radio value={'0'}>定额</Radio>
                <Radio value={'1'}>比例</Radio>
              </Radio.Group>)}
          </Form.Item>}
          {(record[0] && record[0].status == '1' || isCheck) && <Form.Item label="员工收银提成比例">
            {getFieldDecorator('commissionValue', {
              initialValue: record[0] && record[0].commissionValue,
            })(<Input 
                addonAfter={type}
              />)}
          </Form.Item>}
        </Form>
      </Modal>
    </PageHeaderWrapper>
    )
}

export default Form.create()(Cashier)
